import React from 'react';
import { 
  Upload, 
  Button, 
  Select,
  Typography,
  Alert,
  Space,
  message,
  Progress,
  Card,
  Spin
} from 'antd';
import { 
  LoadingOutlined,
  InboxOutlined,
  DeleteOutlined,
  ScanOutlined,
  CopyOutlined
} from '@ant-design/icons';
import { pdfService } from '../services/pdfService';
import type { UploadProps } from 'antd';
import styles from './OCRConverter.module.css';
import PageHeader from './PageHeader';
import { APIError } from '../services/pdfService';

const { Dragger } = Upload;
const { Option } = Select;
const { Text, Title, Paragraph } = Typography;

const OCRConverter: React.FC = () => {
  const [selectedFile, setSelectedFile] = React.useState<File | null>(null);
  const [recognizing, setRecognizing] = React.useState(false);
  const [error, setError] = React.useState<string>('');
  const [progress, setProgress] = React.useState(0);
  const [result, setResult] = React.useState<string>('');
  const [lang, setLang] = React.useState<string>('chi_sim+eng');

  const handleFileSelect = (info: any) => {
    const file = info.file;
    if (!file) return;

    setError('');
    setProgress(0);
    setResult('');

    // 验证文件类型
    const isValidType = file.type === 'application/pdf' || 
                       file.type.startsWith('image/');
    const maxSize = 50 * 1024 * 1024; // 50MB

    if (!isValidType) {
      setError('请上传PDF或图片文件（JPG、PNG）');
      return;
    }

    if (file.size > maxSize) {
      setError('文件大小不能超过50MB');
      return;
    }

    setSelectedFile(file);
  };

  const handleRecognize = async () => {
    if (!selectedFile) {
      message.warning('请先选择文件');
      return;
    }

    try {
      setRecognizing(true);
      setError('');
      setProgress(0);
      setResult('');
      
      const response = await pdfService.ocrFile(selectedFile, lang);
      
      if (response.code === 200 && response.data?.text) {
        setProgress(100);
        setResult(response.data.text);
        message.success('识别成功！');
      } else {
        throw new APIError('识别失败，返回数据格式错误');
      }
    } catch (error) {
      let errorMessage = '识别失败';
      
      if (error instanceof APIError) {
        switch (error.status) {
          case 413:
            errorMessage = '文件太大，请上传小于50MB的文件';
            break;
          case 415:
            errorMessage = '不支持的文件类型，请上传PDF或图片文件';
            break;
          case 422:
            errorMessage = '文件验证失败，请确保文件格式正确';
            break;
          case 429:
            errorMessage = '请求过于频繁，请稍后再试';
            break;
          default:
            errorMessage = error.message;
        }
      } else {
        errorMessage = '识别过程出错，请稍后重试';
      }

      setError(errorMessage);
      message.error(errorMessage);
    } finally {
      setRecognizing(false);
    }
  };

  const handleCopy = () => {
    if (result) {
      navigator.clipboard.writeText(result)
        .then(() => message.success('文本已复制'))
        .catch(() => message.error('复制失败'));
    }
  };

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    accept: '.pdf,image/*',
    showUploadList: false,
    beforeUpload: () => false,
    onChange: handleFileSelect,
  };

  return (
    <div className={styles.container}>
      <PageHeader title="OCR文字识别" />
      <Card className={styles.converterCard}>
        <Title level={4} className={styles.cardTitle}>
          OCR文字识别
          <Select 
            value={lang} 
            onChange={setLang}
            className={styles.langSelect}
          >
            <Option value="chi_sim+eng">中文+英文</Option>
            <Option value="chi_sim">中文</Option>
            <Option value="eng">英文</Option>
          </Select>
        </Title>

        <div className={styles.uploadSection}>
          {!selectedFile ? (
            <Dragger {...uploadProps} className={styles.draggerContainer}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined className={styles.uploadIcon} />
              </p>
              <p className={styles.uploadText}>
                点击或拖拽文件到此区域
              </p>
              <p className={styles.uploadHint}>
                支持PDF和图片文件（JPG、PNG），大小不超过50MB
              </p>
            </Dragger>
          ) : (
            <div className={styles.fileInfo}>
              <div className={styles.fileDetails}>
                <span className={styles.fileName}>{selectedFile.name}</span>
                <span className={styles.fileSize}>
                  {(selectedFile.size / (1024 * 1024)).toFixed(2)}MB
                </span>
              </div>
              <Space>
                <Button 
                  icon={<DeleteOutlined />}
                  onClick={() => {
                    setSelectedFile(null);
                    setError('');
                    setProgress(0);
                    setResult('');
                  }}
                >
                  删除
                </Button>
                <Button
                  type="primary"
                  icon={recognizing ? <LoadingOutlined /> : <ScanOutlined />}
                  onClick={handleRecognize}
                  loading={recognizing}
                  disabled={!!error}
                >
                  {recognizing ? '识别中...' : '开始识别'}
                </Button>
              </Space>
            </div>
          )}
        </div>

        {error && (
          <Alert
            message="错误"
            description={error}
            type="error"
            showIcon
            className={styles.alert}
          />
        )}

        {recognizing && (
          <div className={styles.progressContainer}>
            <Progress 
              percent={progress} 
              status={progress === 100 ? "success" : "active"}
              strokeColor={{
                '0%': '#108ee9',
                '100%': '#87d068',
              }}
            />
          </div>
        )}

        {result && (
          <div className={styles.resultContainer}>
            <div className={styles.resultHeader}>
              <Text strong>识别结果</Text>
              <Button 
                type="link" 
                icon={<CopyOutlined />}
                onClick={handleCopy}
              >
                复制文本
              </Button>
            </div>
            <div className={styles.resultContent}>
              <pre>{result}</pre>
            </div>
          </div>
        )}
      </Card>
    </div>
  );
};

export default OCRConverter; 